<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
        <el-form-item label="统计日期" prop="timeScopes">
          <el-date-picker
            v-model="timeScopes"
            @change="validateYearRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productCodes">
          <el-select
            multiple
            v-model="queryParams.productCodes"
            placeholder="请选择产品名称"
            clearable
            class="!w-[192px]"
            @change="typeChange"
          >
            <el-option
              v-for="item in optionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="p0">
      <div class="rounded-lg w-full bg-white p-6 shadow-sm mt-8">
        <div class="mb-4 flex items-center justify-between">
          <div class="text-lg font-medium">价格趋势分析</div>
          <!-- <div class="flex items-center gap-4">
                <el-checkbox-group v-model="selectedMetrics">
                  <el-checkbox-button
                    v-for="metric in metrics"
                    :key="metric.key"
                    :label="metric.key"
                  >
                    {{ metric.label }}
                  </el-checkbox-button>
                </el-checkbox-group>
              </div> -->
        </div>
        <div ref="chartRef" style="width: 100%" class="h-[400px] w-full"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { ref, onMounted, watch, computed } from "vue";
import { FormItemRule } from "element-plus/es";
import type { EChartsOption, SeriesOption } from "echarts";
import { downLoad, historyDownLoad } from "@/utils/downLoad";
import statementApi, {
  CustomerReportPageQuery,
  locationPageQuery,
} from "@/api/statement/statement";
import * as echarts from "echarts";
import configApi, { ConfigType } from "@/api/config/config";
const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts;
const timeScopes = ref([]);
// 限制选择范围不超过365天
const validateYearRange = (val: any) => {
  if (!val || val.length !== 2) {
    return;
  }

  const [start, end] = val;
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算两个日期之间的年份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear();
  const monthDiff = endDate.getMonth() - startDate.getMonth();
  const dayDiff = endDate.getDate() - startDate.getDate();

  // 如果年份差大于1年，或者正好1年但结束月份/日期大于开始月份/日期
  if (yearDiff > 1 || (yearDiff === 1 && (monthDiff > 0 || (monthDiff === 0 && dayDiff > 0)))) {
    ElMessage.error(`选择的时间范围不能超过一年`);

    timeScopes.value = [];
  }
};
const handleTabClick = () => {
  nextTick(() => {
    chart?.resize();
  });
};
const activeList = ref([
  { label: "报表", value: 1 },
  { label: "统计图", value: 2 },
]);
const activeTab = ref(1);
const typeChange = (val: any) => {};
// 时间
const dataList = ref([
  { label: "天", value: 0 },
  { label: "周", value: 1 },
  { label: "月", value: 2 },
  { label: "季度", value: 3 },
  { label: "年", value: 4 },
]);
const metrics = [
  { key: "price", label: "当前价格" },
  { key: "yoyPrice", label: "同比价格" },
  { key: "momPrice", label: "环比价格" },
  { key: "zhurou", label: "猪肉" },
  { key: "niurou", label: "牛肉" },
];

const selectedMetrics = ref(["price", "yoyPrice", "momPrice"] as any);
const initChart = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    updateChart();
  }
};
// 方法1：使用reduce
const groupByTime = (data: any[]) => {
  // 1. 先按 productName 分组
  const grouped = data.reduce((acc: any, item: any) => {
    const { productName, ...rest } = item;
    if (!acc[productName]) {
      acc[productName] = [];
    }
    acc[productName].push(rest);
    return acc;
  }, {});

  // 2. 对每个 productName 的日期进行去重和补0
  Object.keys(grouped).forEach((productName) => {
    const items = grouped[productName];

    // 收集所有可能的日期
    const allDates = [...new Set(data.map((item) => item.time))].sort();

    // 构建日期映射，确保每个日期都有数据（没有则补0）
    const dateMap = new Map();
    items.forEach((item: any) => {
      dateMap.set(item.time, item);
    });

    // 填充缺失的日期
    const filledItems = allDates.map((date) => {
      if (dateMap.has(date)) {
        return dateMap.get(date);
      } else {
        return {
          time: date,
          price: "0",
        };
      }
    });

    grouped[productName] = filledItems;
  });

  return grouped;
};
const updateChart = () => {
  chart.setOption(
    {
      series: [], // 先清空系列
    },
    true
  );
  // if (tableData.value.length == 0) return;

  let data = groupByTime(tableData.value);
  console.log(data);
  const dates = [...new Set(tableData.value.map((item: any) => item.time))];
  const title = [...new Set(tableData.value.map((item: any) => item.productName))];

  console.log(dates);
  console.log(title);
  console.log();
  let currentList: SeriesOption[] = [];
  let titleList = [];
  if (queryParams.productCodes?.length == 1) {
    titleList = ["当前价格", "同比价格", "环比价格"];
    currentList = [
      {
        name: "当前价格",
        type: "line",
        smooth: true,
        data: tableData.value.map((item: any) => item.price || 0),
      },
      {
        name: "同比价格",
        type: "line",
        smooth: true,
        data: tableData.value.map((item: any) => item.yoyPrice || 0),
      },
      {
        name: "环比价格",
        type: "line",
        smooth: true,
        data: tableData.value.map((item: any) => item.momPrice || 0),
      },
    ];
  } else if (queryParams.productCodes?.length != 0) {
    title.forEach((item) => {
      // console.log(data[item.productName], "data[item.productName]");
      // let list = Object.keys(data).map((items) => items == item.productName);
      console.log(item);
      console.log(data[item]);
      currentList.push({
        name: item,
        type: "line",
        smooth: true,
        data: data[item].map((items: any) => items.price || 0),
      });
    });
    let listL = optionList.value
      .filter((item: any) => queryParams.productCodes?.join(",").includes(item.value))
      .map((item) => item.label);
    console.log(listL, "listL");
    titleList = listL as any;
    listL.forEach((item) => {
      if (!currentList.some((items) => items.name == item)) {
        currentList.push({
          name: item,
          type: "line",
          smooth: true,
          data: dates.map((items: any) => 0),
        });
      }
    });
    // [{id:1,name:'aaa'},{id:2,name:'bbb'},{id:3,name:'ccc'}] [1,2]
    // if (title.length != queryParams.productCodes?.length) {
    //   queryParams.productCodes?.forEach((item) => {
    //     let name = optionList.value.find((items) => items.value == item)?.label;
    //   });
    // }
    // let listL = (queryParams.productCodes?.length||0)-(title.length)
    // if(listL>0){
    //   listL
    // }
  }
  console.log(currentList, "currentList");
  console.log(titleList, "titleList");

  const option: EChartsOption = {
    animation: false,
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: titleList,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: [
      {
        type: "value",
        name: "金额(元)",
        position: "left",
        axisLabel: {
          formatter: "{value}",
        },
      },
    ],
    series: currentList,
  };
  console.log(option);
  chart.setOption(option);
};
// 加载loading
const loading = ref(false);
// 搜索ref
const queryFormRef = ref(ElForm);
// 一级弹窗ref
const dialogFormRef = ref(ElForm);
//一级弹窗
const dialogVisible = reactive({ visible: false, title: "", type: "" });
//一级表单验证
const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
});
// 类型
const optionList = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getContractLists = () => {
  configApi
    .getProductList({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      console.log(data, "data");
      // rowTableData.value = data?.list || [];
      optionList.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .catch((error) => {
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
};

const queryParams: CustomerReportPageQuery = reactive({
  // timeType: "day",
  productCodes: [],
});

// 类型
const typeList = ref([
  { label: "猪肉", value: 0 },
  { label: "牛肉", value: 1 },
]);

// 列表参数
const tableData = ref([]);

const dialogFormData: {
  id?: string;
  name?: string;
  type?: number;
} = reactive({});

// 查询方法
const handleSeach = () => {
  if (queryParams.productCodes?.length == 0) {
    ElMessage.error(`请选择产品名称查询`);
  } else {
    loading.value = true;
    queryParams.startDate = timeScopes.value[0];
    queryParams.endDate = timeScopes.value[1];
    statementApi
      .getProductPriceReport(queryParams)
      .then((data) => {
        tableData.value = [...(data as never)];
        // console.log(val);
        if (queryParams.productCodes?.length == 1) {
          selectedMetrics.value = ["price", "yoyPrice", "momPrice"] as any;
        } else {
          selectedMetrics.value = ["zhurou", "niurou"] as any;
        }
        updateChart();
      })
      .finally(() => {
        loading.value = false;
      });
  }
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();

  timeScopes.value = [];
  tableData.value = [];
  updateChart();
};

onMounted(() => {
  // handleSeach();
  getContractLists();
  initChart();
  window.addEventListener("resize", () => {
    chart?.resize();
  });
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
.el-checkbox-button :deep(.el-checkbox-button__inner) {
  border-radius: 4px;
  margin-right: 8px;
  border: 1px solid #dcdfe6;
}
.el-checkbox-button.is-checked :deep(.el-checkbox-button__inner) {
  border-color: var(--el-color-primary);
}
:deep(.el-card__body) {
  padding: 0 20px !important;
}
</style>
